#include "daemon_runner.h"
#include "daemon_process.h"
#include "log/log.h"
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <fcntl.h>

#define DAEMON_PROCESS_MAX 2

static DaemonProcess daemon_process_handle[DAEMON_PROCESS_MAX];
static int is_running = 1;

void daemon_runner_signal_handler(int sig)
{
    log_info("Received signal %d, exiting...\n", sig);
    is_running = 0;
}

void daemon_runner_run()
{
    // 将进程后台化
    if (daemon(0, 1) < 0)
    {
        log_fatal("Daemonize failed");
        exit(EXIT_FAILURE);
    }

    // 手动处理标准输入输出和错误输出
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    unlink(LOG_FILE);

    open("/dev/null", O_RDWR);
    open(LOG_FILE, O_RDWR | O_CREAT, 0644);
    dup2(STDOUT_FILENO, STDERR_FILENO);

    signal(SIGTERM, daemon_runner_signal_handler);

    daemon_process_handle[0] = daemon_process_create("app");
    daemon_process_handle[1] = daemon_process_create("ota");

    while (is_running)
    {
        for (size_t i = 0; i < DAEMON_PROCESS_MAX; i++)
        {
            if (!daemon_process_handle[i])
            {
                log_warn("Daemon_process_handle[%d] is null", i);
                continue;
            }
            daemon_process_checkAndRun(daemon_process_handle[i]);
        }
        // 每隔100ms检查一次
        usleep(100000);
    }

    for (size_t i = 0; i < DAEMON_PROCESS_MAX; i++)
    {
        daemon_process_stop(daemon_process_handle[i]);
        daemon_process_destroy(daemon_process_handle[i]);
    }

    log_info("Daemon runner exit");
}